/**
 * Created by 白雨浓 on 2018/12/4 14:56.
 */
import axios from 'axios';
import Vue from 'vue'
import router from '../../router';

const self = Vue.prototype;

const toast = {
  err(msg) {
  },
};

const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  responseType: 'json',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'User-From': 'fengyan',
  },
});

request.interceptors.request.use(config => {
  return config;
});

const all = (method, path, params, callback) => {
  if (typeof params === 'function') {
    callback = params;
    params = {};
  }

  if (['get', 'delete'].includes(method)) {
    return new Promise((resolve, reject) => {
      request[method](path, {params: params})
        .then(res => {
          if (callback) {
            callback();
          }
          resolve(res.data);
        })
        .catch(err => {
          if (callback) {
            callback();
          }
          handleException(err);
          reject(err);
        });
    });
  } else {
    return new Promise((resolve, reject) => {
      request[method](path, params)
        .then(res => {
          if (callback) {
            callback();
          }
          resolve(res.data);
        })
        .catch(err => {
          if (callback) {
            callback();
          }
          handleException(err);
          reject(err);
        });
    });
  }
};

const handleException = (err) => {
  console.log(err);
  if (!err.response || !err.response.status) {
    toast.err('网络异常...');
    return;
  }
  switch (err.response.status) {
    case 400:
      toast.err(err.response.data.errorMsg);
      break;
    case 403:
      toast.err(err.response.data.errorMsg);
      break;
    case 500:
      toast.err(err.response.data ? err.response.data.errorMsg : '(⊙o⊙)...服务器可能是炸了o(╥﹏╥)o');
      break;
    case 401:
      router.push('/login');
      break;
    default:
      break;
  }
};

export default {
  install(Vue) {
    Vue.prototype.$$axios = axios;
    Vue.prototype.$$request = request;
    Vue.prototype.$$get = (path, params, callback) => all('get', path, params, callback);
    Vue.prototype.$$delete = (path, params, callback) => all('delete', path, params, callback);
    Vue.prototype.$$post = (path, params, callback) => all('post', path, params, callback);
    Vue.prototype.$$put = (path, params, callback) => all('put', path, params, callback);
    Vue.prototype.$$patch = (path, params, callback) => all('patch', path, params, callback);
  }
}